package com.stores.v1.model;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.stores.v1.entity.*;
import com.stores.v1.security.*;
import com.stores.v1.toolset.*;

public class BaseModel implements IModel {
	private IDatabase database;
	private IAccessControl accessControl;

	@Override
	public IDatabase getDatabase() {
		return database;
	}

	@Override
	public void setDatabase(IDatabase database) {
		this.database = database;
	}

	@Override
	public IAccessControl getAccessControl() {
		return this.accessControl;
	}

	@Override
	public void setAccessControl(IAccessControl accessControl) {
		this.accessControl = accessControl;
	}

	/***
	 * 
	 * @param account
	 * @param groupId
	 * @throws DatabaseCommandException
	 * @throws DatabaseInitializationException
	 * @throws SQLException
	 */
	public void addToActivityLog(int personId, int privilegeId)
			throws DatabaseCommandException, DatabaseInitializationException,
			SQLException {
		StringBuilder sql = new StringBuilder();
		Connection connection = this.getDatabase().getOpenConnection();
		sql.append("insert into accountlog(personId,privilegeId,logtime,succesfulAction) values(?,?,now(),1);");
		try {
			PreparedStatement command = connection.prepareStatement(sql
					.toString());
			command.setInt(1, personId);
			command.setInt(2, privilegeId);
			command.executeUpdate();
		} catch (SQLException e) {
			throw new DatabaseCommandException(String.format(
					"Failed to log activity due to [%s]", e.getMessage()));
		} finally {
			this.getDatabase().closeConnection(connection);
		}
	}

	/***
	 * 
	 * @param generatedKeys
	 * @return
	 * @throws DatabaseCommandException
	 */
	protected int getGeneratedKey(ResultSet generatedKeys)
			throws DatabaseCommandException {
		try {
			if (generatedKeys.next()) {
				return generatedKeys.getInt(1);
			}
		} catch (SQLException e) {
			throw new DatabaseCommandException(
					String.format(
							"Failed to retrieve generated keys after insert due to [%s]",
							e.getMessage()));
		}
		throw new DatabaseCommandException(
				"Failed to retrieve generated keys after insert as there are none");
	}

	/***
	 * 
	 * @param person
	 * @return
	 */
	protected int getGroupIdByPerson(Person person) {
		int securityGroupId = 0;
		if (person.getClass().equals(SiteAdmin.class)) {
			securityGroupId = 1;
		}
		if (person.getClass().equals(SiteManager.class)) {
			securityGroupId = 2;
		}
		if (person.getClass().equals(StoreAdmin.class)) {
			securityGroupId = 3;
		}
		if (person.getClass().equals(StoreManager.class)) {
			securityGroupId = 4;
		}
		if (person.getClass().equals(Customer.class)) {
			securityGroupId = 5;
		}
		if (person.getClass().equals(Guest.class)) {
			securityGroupId = 6;
		}
		return securityGroupId;
	}
}
